// 一些基础公共方法
import {
	BASEURL,
	EXPATH
} from '@/rule/index.js';

import {
	pinyin
} from './const.js'

/**
 * 为空判断
 * {},[],'',undefined,'undefined',null,'null'
 * @param v
 * @returns {boolean}
 */
const isEmpty = (v) => {
	if (v && typeof v === 'object') {
		return Object.keys(v).length === 0;
	} else if (Array.isArray(v)) {
		return v.length === 0;
	}
	return v === '' || v === 'undefined' || v === undefined || v === null || v === 'null';
};

/**
 * 将json转换为地址栏参数格式
 * @param obj
 * @returns {string}
 */
const jsonToParam = (obj) => {
	let str = '';
	for (let key in obj) {
		str += `${key}=${obj[key]}&`;
	}
	str = str.slice(0, -1);
	return str;
};

/**
 * 地址跳转
 * @param url
 * @param opt JSON格式的参数
 * @param newWin Boolean 是否打开新窗口
 */
const turnToNextPage = (url, opt, newWin) => {
	let u = opt && Object.keys(opt).length > 0 ? `${url}?${jsonToParam(opt)}` : url;
	if (newWin) {
		window.open(u);
	} else {
		window.location.href = u;
	}
};


/**
 * 检查手机号码格式
 */
const checkMobile = (v) => {
	let regular = /^[1][0-9]{10}$|^\d{3}-\d{7,8}|\d{4}-\d{7,8}$/;
	let re = new RegExp(regular);
	if (!re.test(v)) {
		return false;
	}
	return true;
}
/**
 * 检查密码是否符合标准
 * 至少包含一个数字和字母，且6-18位
 */
const checkPassword = (v) => {
	let regular = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/;
	let re = new RegExp(regular);
	if (!re.test(v)) {
		return false;
	}
	return true;
}

/**
 * 时间格式化
 */
const formtimedata = (val, type = '-') => {
	val = val * 1;
	let date = new Date(val);
	if (val && val.toString().length < 12) {
		date = new Date(parseInt(val) * 1000);
	}
	let year = date.getFullYear();
	let month = date.getMonth() + 1 >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1);
	let day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
	let hour = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
	let minute = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
	let scen = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();
	if (type == '-') {
		return year + '-' + month + '-' + day
	} else if (type == '.')
		return year + '.' + month + '.' + day
	else if (type == ':')
		return year + '-' + month + '-' + day + ' ' + hour + ':' + minute
	else
		return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + scen
}

const formvali = (v) => {
	var result = {
		type: true,
		msg: ''
	}
	return new Promise((resolve, reject) => {
		for (var key in v) {
			if (!v[key].unrequired && isEmpty(v[key].value)) {
				resolve(result = {
					type: false,
					msg: v[key].name
				});
			}
		}
		resolve(result)
	})
}

/**
 * 错误信息
 */
const errormsg = (title = '无效访问', url = '/') => {
	uni.showToast({
		title,
		icon: 'loading',
		mask: true,
		complete() {
			setTimeout(() => {
				uni.redirectTo({
					url
				})
			}, 1000)

		}
	})
}

/**
 * 弹出消息框
 */
const msg = (title, url = '', duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
	if (url) {
		setTimeout(() => {
			uni.redirectTo({
				url
			})
		}, 1000)
	}
}

const requestUrl = (v = 'API_URL') => {
	console.log(process.env.VUE_APP_ENV);
	if (process.env.VUE_APP_ENV === 'test') {
		const result = BASEURL.TEST_BASE_URL[v].name; //读取测试环境地址
		return result;
	} else if (process.env.VUE_APP_ENV === 'formal') {
		// console.log('正式环境');
		const result = BASEURL.FORMAL_BASE_URL[v].name; //读取正式环境地址
		return result;
	} else {
		const result = BASEURL.LOCAL_API_URL[v].name; //读取开发环境地址
		return result;
	}
}

//校验当前页面是否登录
const islogin = () => {
	if (getCurrentPages()[getCurrentPages().length - 1]) {
		let exurl = getCurrentPages()[getCurrentPages().length - 1].route;
		if (exurl) {
			if (EXPATH.indexOf(exurl) == -1) {
				if (uni.getStorageSync('LOGIN_INFO')) {} else {
					uni.showToast({
						title: '请先登录',
						icon: 'none',
						duration: 1000
					})
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/users/login'
						})
					}, 800)
				}
			}
		}
	}
}

const getUrl = (url) => {
	return url.startsWith('http://') || url.startsWith('https://');
}

/**
 * 节流
 */
const throttle = (func, wait) => {
	let __previous = 0;
	return function() {
		let now = Date.now();
		let context = this;
		let args = arguments;
		if (now - __previous > wait) {
			func.apply(context, args);
			__previous = now;
		}
	}
}

/**
 * 将数组按规定字段转成对象
 * @param key
 * @param list
 * @returns {{}}
 */
const listToObject = (key, list) => {
	if (isEmpty(list) || !Array.isArray(list)) return {};
	const result = {};
	list.forEach((row) => {
		result[row[key]] = row;
	});
	return result;
};

const chineseToPinYin = function(l1) {
	var l2 = l1.length
	var I1 = ''
	var reg = new RegExp('[a-zA-Z0-9]')
	for (var i = 0; i < l2; i++) {
		var val = l1.substr(i, 1)
		var name = arraySearch(val, pinyin)
		if (reg.test(val)) {
			I1 += val
		} else if (name !== false) {
			I1 += name
		}
	}
	I1 = I1.replace(/ /g, '-')
	while (I1.indexOf('--') > 0) {
		I1 = I1.replace('--', '-')
	}
	return I1
}

const arraySearch = function(l1, l2) {
	for (var name in pinyin) {
		if (pinyin[name].indexOf(l1) !== -1) {
			return ucfirst(name)
		}
	}
	return false
}

const ucfirst = function(l1) {
	if (l1.length > 0) {
		var first = l1.substr(0, 1).toUpperCase()
		var spare = l1.substr(1, l1.length)
		return first + spare
	}
}

export default {
	isEmpty,
	checkMobile,
	checkPassword,
	msg,
	formtimedata,
	errormsg,
	islogin,
	requestUrl,
	formvali,
	throttle,
	getUrl,
	listToObject,
	chineseToPinYin,
	jsonToParam,
	turnToNextPage
}